﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHibernate;
using NHibernate.Cfg;

namespace RushTracker.Core.Data
{
    public class NHibernateSessionFactory
    {
        private static NHibernateSessionFactory _nHibernateSessionFactory = new NHibernateSessionFactory();
        private Configuration _config;
        private ISessionFactory _sessionFactory;

        public NHibernateSessionFactory()
        {
            RegisterCoreClasses();
        }

        public static NHibernateSessionFactory GetInstance()
        {
            return _nHibernateSessionFactory;
        }

        public ISessionFactory GetNHibernateSessionFactory()
        {
            return this._sessionFactory;
        }

        public ISession GetSession()
        {
            return this._sessionFactory.OpenSession();
        }

        private void RegisterCoreClasses()
        {
            Configuration config = new Configuration();
            this._config = config.AddAssembly(this.GetType().Assembly);

            // hack to support relative urls
            this._config.Properties["connection.connection_string"] = String.Format(this._config.Properties["connection.connection_string"], Site.Instance.ResolveUrl(Site.Instance.SQLiteDatabasePath));

            this._sessionFactory = this._config.BuildSessionFactory();
        }
    }
}
